package fun.tan90.easy.binlog.manager.rest;


import cn.hutool.core.util.StrUtil;
import fun.tan90.easy.binlog.base.constants.EasyBinlogConstants;
import fun.tan90.easy.binlog.base.convention.Res;
import fun.tan90.easy.binlog.manager.dict.Dict;
import fun.tan90.easy.binlog.manager.dict.DictItem;
import fun.tan90.easy.binlog.manager.model.vo.SysInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.List;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/7/13 11:08
 */
@Slf4j
@RestController
@RequestMapping("sys")
public class SysController {

    @Resource
    MetricsEndpoint metricsEndpoint;

    /**
     * 应用构建信息
     *
     * @return
     */
    @GetMapping("build-info")
    public Res<SysInfoVo> buildInfo() {
        Double upTimeSeconds = metricsEndpoint.metric("process.uptime", null).getMeasurements().get(0).getValue();
        Duration duration = Duration.ofSeconds(Math.round(upTimeSeconds));
        long seconds = duration.getSeconds() % 60;
        long minutes = duration.toMinutes() % 60;
        long hours = duration.toHours() % 24;
        long days = duration.toDays();
        String upTime = StrUtil.format("{}{}{}{}", days > 0 ? days + "day " : "", hours > 0 ? hours + "hour " : "", minutes > 0 ? minutes + "min " : "", seconds > 0 ? seconds + "sec" : "");
        return Res.ok(SysInfoVo.builder()
                .version(EasyBinlogConstants.VERSION)
                .upTime(upTime)
                .startUpTime(EasyBinlogConstants.START_UP_TIME)
                .build());
    }

    /**
     * 字典列表
     *
     * @param dictType
     * @return
     */
    @GetMapping("dict")
    public List<DictItem> dict(String dictType) {
        return Dict.dict(dictType);
    }

}
